from datetime import datetime, timedelta
from flask import Blueprint, request
from models.models import SensorData, db
from utils.helpers import api_response

sensor_bp = Blueprint('sensor', __name__)

@sensor_bp.route('/data', methods=['POST'])
def submit_sensor_data():
    """
    提交传感器数据
    ---
    tags:
      - 传感器数据
    parameters:
      - name: body
        in: body
        required: true
        schema:
          type: object
          required:
            - sensor_type
            - sensor_value
          properties:
            sensor_type:
              type: string
              description: 传感器类型
            sensor_value:
              type: number
              description: 传感器读数值
            alarm_level:
              type: string
              description: 警报级别
              default: Normal
    responses:
      200:
        description: 数据提交成功
        schema:
          type: object
          properties:
            code:
              type: integer
              example: 200
            message:
              type: string
              example: "数据提交成功"
            data:
              type: object
              properties:
                data_id:
                  type: integer
                  description: 数据记录ID
      400:
        description: 参数错误
      500:
        description: 服务器内部错误
    """
    try:
        data = request.json
        required_fields = ['sensor_type', 'sensor_value']
        if not all(key in data for key in required_fields):
            return api_response(message="缺少必要字段", code=400, status_code=400)
            
        new_data = SensorData(
            sensor_type=data['sensor_type'],
            sensor_value=float(data['sensor_value']),
            alarm_level=data.get('alarm_level', 'Normal')
        )
        
        db.session.add(new_data)
        db.session.commit()
        
        return api_response(
            data={"data_id": new_data.data_id},
            message="数据提交成功",
            code=200
        )
    except ValueError:
        return api_response(message="数值格式错误", code=400, status_code=400)
    except Exception as e:
        db.session.rollback()
        return api_response(message=str(e), code=500, status_code=500)

@sensor_bp.route('/history', methods=['GET'])
def get_sensor_history():
    """
    获取传感器历史数据
    ---
    tags:
      - 传感器数据
    parameters:
      - name: type
        in: query
        type: string
        required: false
        description: 传感器类型过滤
      - name: hours
        in: query
        type: integer
        required: false
        description: 查询过去多少小时的数据
        default: 24
    responses:
      200:
        description: 查询成功
        schema:
          type: object
          properties:
            code:
              type: integer
              example: 200
            data:
              type: array
              items:
                type: object
                properties:
                  id:
                    type: integer
                    description: 数据ID
                  type:
                    type: string
                    description: 传感器类型
                  value:
                    type: number
                    description: 传感器值
                  alarm_level:
                    type: string
                    description: 警报级别
                  time:
                    type: string
                    description: 时间戳(ISO格式)
      500:
        description: 服务器内部错误
    """
    try:
        sensor_type = request.args.get('type')
        hours = request.args.get('hours', 24, type=int)
        
        time_threshold = datetime.utcnow() - timedelta(hours=hours)
        
        query = SensorData.query.filter(
            SensorData.timestamp >= time_threshold
        )
        
        if sensor_type:
            query = query.filter_by(sensor_type=sensor_type)
            
        records = query.order_by(SensorData.timestamp.desc()).all()
        
        result = [{
            "id": record.data_id,
            "type": record.sensor_type,
            "value": float(record.sensor_value),
            "alarm_level": record.alarm_level,
            "time": record.timestamp.isoformat()
        } for record in records]
        
        return api_response(data=result, code=200)
    except Exception as e:
        return api_response(message=str(e), code=500, status_code=500) 